//
//  YCDetailsViewController.m
//  LOLBox
//
//  Created by mac on 15-3-13.
//  Copyright (c) 2015年 Honey. All rights reserved.
//

#import "YCDetailsViewController.h"
#import "AFNetworking.h"
#import "YCNewSModel.h"
#import "HTMLNode.h"
#import "HTMLParser.h"
#import "YCDetailModel.h"
#import "YCCommentView.h"
#import "YCCommentModel.h"
#import "YCCommentViewController.h"
#import "YCAppDelegate.h"
#import <ShareSDK/ShareSDK.h>

#define kDetailsUrl @"http://lolbox.oss.aliyuncs.com/json/v3/news/content/%@.json?r=350667"
#define kCommentUrl @"http://115.28.43.55/lol/index.php/UserSdk/hotCommentList/orderBy/hot/entity_id/%@/entity_type/news"

@interface YCDetailsViewController ()<UIWebViewDelegate>
{
    NSMutableArray *_dataSource;
    UIScrollView *_scrollView;
    UIView *_titleView;
    UIView *_commentView;
    UIWebView *_webView;
    UIView *_comVi;
    NSString *_path;
    CGFloat heg;
}

@end

@implementation YCDetailsViewController

//详情出现的时候隐藏TabBar
- (void)viewWillAppear:(BOOL)animated
{
    YCAppDelegate *delegate = [UIApplication sharedApplication].delegate;
    [delegate hideTabBar];
    
    NSLog(@"这是随机数;: %d",arc4random() % 10);
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _dataSource = [NSMutableArray array];
        self.automaticallyAdjustsScrollViewInsets = NO;
        //Title
        [self createNavTitleView:@"内容"];
        //左边按钮
        [self createBackBarBtnWithTarget:self WithAction:@selector(popTheView)];
        
        
        // 右边按钮
        [self createCommonBarBtn];
        
    }
    return self;
}
- (void)popTheView
{
    if (_dataSource.count > 0)
    {
        NSLog(@"清数据");
        [_dataSource removeAllObjects];
    }
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self createTheView];
    [self createCom];
}

// 实例化界面
- (void)createTheView
{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64)];
    _titleView = [[UIView alloc] initWithFrame:CGRectMake(5, 5, 310, 77)];
    _commentView = [[UIView alloc] init];
    
    _commentView.backgroundColor = [UIColor redColor];
    _scrollView.backgroundColor = [UIColor whiteColor];
    //_titleView.backgroundColor = [UIColor blueColor];
    
    [_scrollView addSubview:_titleView];
    [self.view addSubview:_scrollView];
}

- (void)senderNewsModel:(YCNewSModel *)NewsModel
{
    [_dataSource removeAllObjects];
    NSString *IdStr = (NSString *)NewsModel.Id;
    _path = IdStr;
    NSString *bbjStr = [NSString stringWithFormat:kDetailsUrl,IdStr];
    [self AFN:bbjStr];
    [self AFNComment:kCommentUrl];
}
- (void)senderBannerId:(NSString *)str
{
    [_dataSource removeAllObjects];
    NSString *IdStr = str;
    _path = IdStr;
    NSString *bbjStr = [NSString stringWithFormat:kDetailsUrl,IdStr];
    [self AFN:bbjStr];
    [self AFNComment:kCommentUrl];

}

/**
 *  数据请求
 */
- (void)AFN:(NSString *)strUrl
{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:strUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //loadView
        CGRect loadFrame = [[UIScreen mainScreen] bounds];
        loadFrame.size.height = loadFrame.size.height;
        
        YCLoadingVIew *v = [[YCLoadingVIew alloc] initWithFrame:loadFrame withTitle:@"加载中..."];
        [self.view addSubview:v];
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //title
        YCNewSModel *titleModel = [[YCNewSModel alloc] init];
        titleModel.title = dict[@"title"];
        titleModel.desc = dict[@"desc"];
        titleModel.posttime = dict[@"posttime"];
        titleModel.site = dict[@"site"];
        
        /**
         取出content
         */
        NSString *contentString = [NSString stringWithFormat:@"<head>%@</head>",dict[@"content"]];
        //NSLog(@"contenString:%@",contentString);
        
        NSError *error;
        HTMLParser *parser = [[HTMLParser alloc] initWithString:contentString error:&error];
        if (error)
        {
            NSLog(@"Error:%@",error);
            return;
        }
        
        HTMLNode *bodyNode = [parser body];
        NSArray *inputNodes = [bodyNode findChildTags:@"p"];
        
        for (HTMLNode *inputNode in inputNodes)
        {
            if (inputNode.contents.length > 0)
            {
                YCDetailModel *model = [[YCDetailModel alloc] init];
                // 图片
                NSArray *inputNodes2 = [inputNode findChildTags:@"img"];
                for (HTMLNode *imput in inputNodes2)
                {
                    //NSLog(@"图片:%@",[imput getAttributeNamed:@"src"]);
                
                    NSString *img = [imput getAttributeNamed:@"src"];
                    model.pImg = img;
                }
                NSString *content = [inputNode.contents stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                model.pContent = content;
                
                //NSLog(@"内容:%@",inputNode.contents);
                //NSLog(@"社么:%@",inputNode.rawContents);
                //NSLog(@"--------------------------");
            }
        }
        
        [UIView animateWithDuration:3 animations:^{
            v.alpha = 0;
        }];
        [self showContent:contentString];
        [self showTitle:titleModel];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"fail");
    }];
}

//评论数据请求
- (void)AFNComment:(NSString *)str
{
//    if (_dataSource.count > 0)
//    {
//        NSLog(@"先删除数据");
//        [_dataSource removeAllObjects];
//    }
    NSString *s = [NSString stringWithFormat:kCommentUrl,_path];
    //NSLog(@"s= %@",s);
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:s parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        //NSLog(@"qw   :%@",arr);
        [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            YCCommentModel *m = [[YCCommentModel alloc] init];
            m.icon = obj[@"icon"];
            m.content = obj[@"content"];
            m.goodNum = obj[@"good_num"];
            m.postTime = obj[@"post_time"];
            m.uid = obj[@"uid"];
            
            if (![obj[@"username"] isKindOfClass:[NSNull class]])
            {
                m.username = obj[@"username"];
            }
            else
            {
                m.username = @"游客";
            }
            [_dataSource addObject:m];
        }];
        
        [self showComment];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"fail");
    }];
}


- (void)showTitle:(YCNewSModel *)m
{
    UILabel *tit = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_titleView.frame), 50)];
    UILabel *timeAndSite = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, CGRectGetWidth(_titleView.frame), 20)];
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(-5, 75, CGRectGetWidth(_titleView.frame) + 10, 2)];
    
    //tit.backgroundColor = [UIColor yellowColor];
    //timeAndSite.backgroundColor = [UIColor greenColor];
    timeAndSite.textColor = [UIColor grayColor];
    v.backgroundColor = [UIColor lightGrayColor];
    v.alpha = 0.3;
    
    tit.numberOfLines = 0;
    tit.font = [UIFont boldSystemFontOfSize:18];
    timeAndSite.font = [UIFont systemFontOfSize:11];
    
    tit.text = [NSString stringWithFormat:@"%@",m.title];
    timeAndSite.text = [NSString stringWithFormat:@"  更新时间: %@ 来源: %@",m.posttime,m.site];
    [_titleView addSubview:tit];
    [_titleView addSubview:timeAndSite];
    [_titleView addSubview:v];
}

- (void)showContent:(NSString *)str
{
    NSString *bbjStr = [NSString stringWithFormat:kDetailsUrl,_path];
    
    _webView = [[UIWebView alloc] init];
    _webView.frame = CGRectMake(0, CGRectGetMaxY(_titleView.frame) + 5, 320, 480 - 64 - 140);
    _webView.backgroundColor = [UIColor clearColor];
    _webView.scrollView.scrollEnabled = NO;
    _webView.scrollView.showsVerticalScrollIndicator = YES;
    [_webView loadHTMLString:str baseURL:[NSURL URLWithString:bbjStr]];
    
    _webView.delegate = self;
    
}

- (void)showComment
{
    heg = 0;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    titleLabel.text = @"热门评论";
    titleLabel.textColor = [UIColor grayColor];
    titleLabel.backgroundColor = [UIColor lightGrayColor];
    [_commentView addSubview:titleLabel];
    for (NSInteger i = 0; i < _dataSource.count; i++)
    {
        //NSLog(@"11");
        YCCommentView *view = [[YCCommentView alloc] initWithFrame:CGRectMake(0, i * 50 + 30, CGRectGetWidth(_scrollView.frame), 50)];
        //view.backgroundColor = [UIColor redColor];
        YCCommentModel *m = _dataSource[i];
        CGFloat height = [view fillCellWithModel:m];
        //NSLog(@"%f",height);
        CGRect frame = view.frame;
        frame.size.height = height + 20;
        frame.origin.y = heg + 30;
        view.frame = frame;
        heg += height + 31;
        [_commentView addSubview:view];
        
//        UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, i * 40, 320, 40)];
//        v.backgroundColor = [UIColor colorWithRed:arc4random()/225.0 green:1 blue:1 alpha:1];
        //[_commentView addSubview:v];
    }
    
    CGRect comment = _commentView.frame;
    comment.size.height = heg + 63.5;
    _commentView.frame = comment;
}

#pragma -mark webViewdelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //NSLog(@"jingla ");
    [webView stringByEvaluatingJavaScriptFromString:@
    "var script = document.createElement('script');"
    "script.type = 'text/javascript';"
    "script.text = \"function img() { "
    "var myimg,oldwidth;"
    "var maxwidth=300;" //缩放系数
    "for(i=0;i <document.images.length;i++){"
    "myimg = document.images[i];"
    "if(myimg.width > maxwidth){"
    "oldwidth = myimg.width;"
    "myimg.width = maxwidth;"
    "myimg.height = myimg.height * (maxwidth/oldwidth) + 85;"
    "}"
    "}"
    "}\";"
    "document.getElementsByTagName('head')[0].appendChild(script);" ];
    
    [webView stringByEvaluatingJavaScriptFromString:@"img();"];
    
    NSString *height_str= [_webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
    int height = [height_str intValue] + 30;
    _webView.frame = CGRectMake(0,CGRectGetMaxY(_titleView.frame) + 5,320,height);
    //NSLog(@"height: %@", [_webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"]);
    
    //_commentView.frame = CGRectMake(0, CGRectGetMaxY(_webView.frame), 320, _dataSource.count * 40 + 100);
    CGRect frame = _commentView.frame;
    frame.origin.y = CGRectGetMaxY(_webView.frame);
    _commentView.frame = frame;
    
    _scrollView.contentSize = CGSizeMake(0, height + CGRectGetHeight(_titleView.frame) + CGRectGetHeight(_commentView.frame) + 50);
    
    [_scrollView addSubview:_commentView];
    [_scrollView addSubview:_webView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//评论部分
- (void)createCom
{
    _comVi = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame) - 44 - 64, CGRectGetWidth(self.view.frame), 44)];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 44)];
    UIButton *commonBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    UIButton *favBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [favBtn addTarget:self action:@selector(shareTheApp:) forControlEvents:UIControlEventTouchUpInside];
    
    commonBtn.frame = CGRectMake(40, 8, 180, 30);
    favBtn.frame = CGRectMake(230, 0, 40, 40);
    shareBtn.frame = CGRectMake(275, 0, 40, 40);
    
    [favBtn setImage:[UIImage imageNamed:@"imageset_toolbar_share_hi"] forState:UIControlStateNormal];
    [shareBtn setImage:[UIImage imageNamed:@"imageset_toolbar_fav_empty_hi"] forState:UIControlStateNormal];
    [shareBtn setImage:[UIImage imageNamed:@"imageset_toolbar_fav_hi"] forState:UIControlStateHighlighted];
    
    //comVi.backgroundColor = [UIColor brownColor];toolbar_light_background2
    imgView.image = [UIImage imageNamed:@"toolbar_light_background2"];
    [commonBtn setTitle:@"发表评论" forState:UIControlStateNormal];
    [commonBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    commonBtn.titleLabel.alpha = 0.5;
    commonBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    commonBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    
    //commonBtn.backgroundColor = [UIColor lightGrayColor];
    
    [_comVi addSubview:imgView];
    [_comVi addSubview:commonBtn];
    [_comVi addSubview:favBtn];
    [_comVi addSubview:shareBtn];
    [self.view addSubview:_comVi];

}

//创建右侧评论按钮  common_button
- (void)createCommonBarBtn
{
    UIBarButtonItem *barbtn = [[UIBarButtons alloc] createCommonBarButtonWithTarget:self WithAction:@selector(pushComment)];
    UIBarButtonItem *space = [[UIBarButtons alloc] createSpaceButtonWithWidth:-10];
    //右侧评论按钮
    self.navigationItem.rightBarButtonItems = @[space,barbtn];
}

//触发分享的事件
//分享功能
- (void)shareTheApp:(UIButton *)sender
{
    NSLog(@"jinlai ");
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"Default" ofType:@"png"];
    
    //1、构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:@"要分享的内容"
                                       defaultContent:@"默认内容"
                                                image:[ShareSDK imageWithPath:imagePath]
                                                title:@"ShareSDK"
                                                  url:@"http://www.mob.com"
                                          description:@"这是一条演示信息"
                                            mediaType:SSPublishContentMediaTypeNews];
    //1+创建弹出菜单容器（iPad必要）
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    
    //2、弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                //可以根据回调提示用户。
                                if (state == SSResponseStateSuccess)
                                {
                                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                    message:nil
                                                                                   delegate:self
                                                                          cancelButtonTitle:@"OK"
                                                                          otherButtonTitles:nil, nil];
                                    [alert show];
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                                    message:[NSString stringWithFormat:@"失败描述：%@",[error errorDescription]]
                                                                                   delegate:self
                                                                          cancelButtonTitle:@"OK"
                                                                          otherButtonTitles:nil, nil];
                                    [alert show];
                                }
                            }];
    
}

- (void)pushComment
{
    YCCommentViewController *comment = [[YCCommentViewController alloc] init];
    [comment senderId:_path];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:comment animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
